<?php

class FileManagerItem extends DataObjectWed implements FileManagerItemInterface
{
    public $_dbTable = 'file_manager_item';
    public $_dbIndex = 'itemID';
    public $_fileDirPath = '';
    public $_fileUrlPath = '';

    public $file;
    public $_arFields = array('file_name',
                              'file_managerID',
							  'title',
							  'description',
							  'order',
							  'restricted',
                              'type');

    public function __construct($options=array())
    {
        parent::__construct();
		// $options may be used here
		if($options['file_folder'])
		{
			$folder = "/".$options['file_folder'];
		}
        $this->_fileDirPath   = DIR_FILE_UPLOAD ."/". $this->_dbTable.$folder;
        if(!file_exists($this->_fileDirPath)) mkdir($this->_fileDirPath);
        $this->_fileUrlPath = $GLOBALS["CONF"]["url"]["dir_file_upload"] ."/". $this->_dbTable.$folder;
		$this->file = new File();
	}
	
	public function duplicate($id = NULL)
	{
		$newObj = parent::duplicate($id);
		if($newObj->getID())
		{
			// copy all the files related to this item.
			$files = glob($this->_fileDirPath."/".$this->getFileName()."*");
			foreach ( $files as $filename)
			{
				$name = basename($filename);
				// in case there is a suffix wich happens to contain the same filename, split filename and use the first part.
				$splitName = explode("_",$name);
				$newName = $splitName;
				// replace first part with new filename.
				str_replace($this->getFileName(),$newObj->getFileName(),$newName[0]);
				copy($this->_fileDirPath."/".$name,$this->_fileDirPath."/".implode($newName));
			}
		}
	}
	
	protected function loadFile()
	{
		$this->file->type = $this->getExtension();
    	$this->file->dirPath = $this->_fileDirPath;
		$this->file->urlPath = $this->_fileUrlPath;
		$this->file->filename = $this->getFileName();
		$this->file->file_title = $this->getFileTitle();
		$this->file->type = $this->getExtension();		
	}
	public function get($opt)
	{
		if(parent::get($opt))
		{
			$this->loadFile();
			return 1;
		}
		return 0;
	}
	
	public function set($data, $stripslashes = false)
	{
		parent::set($data, $stripslashes);
		$this->loadFile();
	}

    public function upload($filePost)
    {
		$this->file_name = $filePost['name'];
        $this->type = $filePost['type'];
        $this->update();
		// Must set filename here! object was recently created!
        $this->loadFile();
		if(($this->file->catchPost($filePost)==UPLOAD_ERR_OK) && $this->file->savePost())
        {
			return 1;
        }
        $this->delete();
        return 0;
    }
	
    public function delete($id = NULL)
    {
        $id = $id ? $id : $this->getID();
        if(!$id) return 0;
        if(!$this->file && !$this->get($id))
        {
			$this->_error("Por favor, seleccione un archivo v&aacute;lido.");
            return 0;
        }
        if(!$this->file_name)
		{
			return parent::delete($id);
        }
        $this->file->delete();
        return parent::delete($id);
    }

    public function exists()
    {
        if(!$this->getID()) return 0;
        return $this->file->exists();
    }
	
	// returns the name in disk 
    protected function getFileName()
    {
        return $this->getID();
    }
	
	// return the name name of the file in db
	public function getFileTitle()
	{
		return $this->file_name;
	}

    public function download()
    {
	    if (!$this->getID() ) return 0;

        if (!$this->file->download() )
        {
            $this->_error($this->file->getErrorMessage() );
            return 0;
        }
        return 1;
    }

    public function getPath()
    {
        return $this->_fileDirPath."/".$this->getFileName();
    }

	public function getInfoThumb($type = "mediumIcon", $opts = array(), $downloadable = true, $edit = false)
	{
		$clickable = $downloadable ? "clickable" : "";
		$editBtn = $edit ? '<div class="checkboxDiv"><input type="checkbox" name="delFile['.$this->getID().']" value="1"></div> ' : "";
		
		switch($type)
		{
			case "details":
							$str = "<div class='fileDetails ".$clickable." ".(($opts['parity'] % 2) == 0 ? "even" : "odd")."' title='".$this->getFileTitle()."'>";
							$str .= $editBtn;
							$str .= "<div class='fileName'  ".$opts["attr"].">".$this->getFileTitle()."</div>";
							$str .= "<div class='dateModified'  ".$opts["attr"].">".dateFormat($this->date_modified,"d/m/Y H:i:s")."</div>";
							$str .= "<div class='type'  ".$opts["attr"]." >".$this->type."</div>";
							$str .= "</div>";
							break;
			default:
							$str = "<div class='fileThumb ".$type." ".$clickable."' title='".$this->getFileTitle()."'>";
							$str .= "<div class='icon' ".$opts["attr"]." style='background: url(\"".$this->getIconUrl($type)."\")'></div>";
							$str .= $editBtn;
							$str .= "<div class='fileName' ".$opts["attr"].">".$this->getFileTitle()."</div>";
							$str .= "</div>";
							break;
		}
		return $str;
	}
	
	public function getIconUrl($type = "mediumIcon")
	{
		switch($type)
		{
			case "smallIcon": 	$folder = "small";
								break;
			case "largeIcon":	$folder = "large";
								break;
			default			:	$folder = "medium";
								break;
		}					
		
		$iconsUrl = $GLOBALS["CONF"]["url"]["root"]."/images/file_icons/".$folder;
		$iconsDir = DIR_ROOT."/images/file_icons/".$folder;

		$icon = new Image();
		$icon->dirPath = $iconsDir;
		$icon->urlPath = $iconsUrl;
		$ext = strtoupper($this->getExtension());
		$icon->filename = (file_exists($iconsDir."/".$ext.".png") ? $ext : "ARCHIVE" ).".png";
		return $icon->getUrl();
	}
	
	public function getIcon($type, $attr = NULL)
	{
		if($this->exists())
		{
			return "<img ".$attr." src='".$this->getIconUrl($type)."'>";
		}
	}
	
	public function getUrl()
	{
		if($this->exists())
		{
			return $this->_fileUrlPath."/".$this->getFileName();
		}
	}
	
	public function getExtension()
	{
		$ext = explode(".", $this->getFileTitle());
		$ext = $ext[count($ext) -1]; // get the last part.
		return $ext ; 
	}
}


?>
